package cn.sfturing.web;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import cn.sfturing.entity.*;
import cn.sfturing.service.*;
import cn.sfturing.utils.StringAndDate;
import com.alibaba.fastjson.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import cn.sfturing.dao.FavouriteDao;

/**
 * 
 * @author sfturing
 *
 * @date 2017年6月2日
 */
@Controller
public class OrderController {

	@Autowired
	private CommonUserService commnUserService;
	@Autowired
	private OrderRecordsService orderRecordsService;
	@Autowired
	private FavouriteDao favouriteDao;
	@Autowired
	private HospitalService hospitalService;
	@Autowired
	private DoctoWorkService doctoWorkService;
	@Autowired
	private DoctorService doctorService;

	private static Logger log = LoggerFactory.getLogger(OrderController.class);

	/**
	 * 用户预约首页
	 * 
	 * @return
	 */
	@RequestMapping(value = "/orderIndex", method = RequestMethod.GET)
	public String orderIndex() {

		return "order/orderInfo";
	}

	/**
	 * 用户预约
	 * 
	 * @return
	 */
	@RequestMapping(value = "/order", method = RequestMethod.POST)
	public String order(String orderInfoValue, String hospitalName, String officesName, String doctorName,
			String userIdenf, Model model, String doctorImg) {
		// 分解传入的时间以及时间段

		String orderInfoValueArry[] = orderInfoValue.split(",");
		String transact_date = orderInfoValueArry[0];//日期
		String transact_time = orderInfoValueArry[1];//时间段

		CommonUser commonUser = commnUserService.findCommonUserByUserIdenf(userIdenf);
		OrderRecords orderRecords = new OrderRecords();
		// 设置orderRecords
		orderRecords.setUserID((int) commonUser.getUserId());
		orderRecords.setTransactTime(transact_time);
		orderRecords.setTransactDate(transact_date);
		orderRecords.setHospitalName(hospitalName);
		orderRecords.setOfficesName(officesName);
		orderRecords.setDoctorName(doctorName);
		// 设置预约识别码 0代表只选择时间段，未提交订单
		orderRecords.setOrderVer(0);
		//创建时间
		orderRecords.setCreateTime(new StringAndDate().getString2(new Date()));
		log.info("插入订单，待提交！");
		// 插入订单
		orderRecordsService.insertOrderRecords(orderRecords);
		// 设置最后插入的id(不会发生并发性问题，是根据线程查询的)

		//得到插入的对象
		OrderRecords orderRecords1=orderRecordsService.queryOne(orderRecords);
		System.out.println(orderRecords1);
		//int id = orderRecordsService.findLastId();

		//orderRecords.setId(id);

		model.addAttribute("orderRecords", orderRecords1);
		model.addAttribute("commonUser", commonUser);
		model.addAttribute("doctorImg", doctorImg);
		return "order/orderInfo";
	}

	/**
	 * 提交订单
	 * 
	 * @return
	 */
	@RequestMapping(value = "/orderUserCenter", method = RequestMethod.POST)
	public String OrderUserCenter(Model model, int userID, int id, String diseaseInfo, HttpSession session) {
		// 得到用户的收藏记录
		List<Favourite> favourites = favouriteDao.findFavHos(userID);
		List<Hospital> hospitals = null;
		if (favourites.size() != 0) {
			hospitals = hospitalService.findFavHos(favourites);
		}
		model.addAttribute("hospitals", hospitals);
		// 得到用户的信息
		CommonUser commonUser = (CommonUser) session.getAttribute("userInfo");
		model.addAttribute("commonUser", commonUser);
		orderRecordsService.updateOrderSta1(id);
		orderRecordsService.updateOrderdiseaseInfo(diseaseInfo, id);

		//修改医生预约时段状态
		doctoWorkService.addDoctoWork(id);
		// 通过userId查询所有订单，为个人中心提供
		List<OrderRecords> orderRecords = orderRecordsService.findOrderRecordsByUserID(userID);
		log.info("插入订单，已提交订单！");
		model.addAttribute("orderRecords", orderRecords);
		return "userCenter/userCenter";
	}

	/**
	 * 取消订单
	 */
	@RequestMapping(value = "/cancelOrder/{id}", method = RequestMethod.POST)
	public String cancelOrder(Model model, @PathVariable(value = "id") int id, HttpSession session) {
		// 通过id更改订单状态
		orderRecordsService.cancelOrder(id);
		//修改医生预约时段状态
		OrderRecords orderRecords1 = orderRecordsService.selectOrderSta1(id);//查找订单信息
		Doctor doctor = doctorService.findDoctorByName(orderRecords1.getDoctorName(),orderRecords1.getOfficesName(),orderRecords1.getHospitalName());//跟据医院名、科室名、医生名字得到医生
		DoctoWork doctoWork = doctoWorkService.selecrByIdAndDateOne(doctor.getId(), orderRecords1.getTransactDate());//根据医生ID、和日期得到预约状态
		if(orderRecords1.getTransactTime().equals("8:00-11:00")){
			doctoWork.setTimeS("0");
		}else if(orderRecords1.getTransactTime().equals("13:00-15:00")){
			doctoWork.setTimeZ("0");
		}else {
			doctoWork.setTimeX("0");
		}
		doctoWork.setGmtModified(new Date());
		doctoWorkService.updateByIdAndDate(doctoWork);
		CommonUser commonUser = (CommonUser) session.getAttribute("userInfo");
		if (commonUser != null) {
			// 得到用户的收藏记录
			List<Favourite> favourites = favouriteDao.findFavHos(commonUser.getUserId());
			List<Hospital> hospitals = null;
			if (favourites.size() != 0) {
				hospitals = hospitalService.findFavHos(favourites);
			}
			model.addAttribute("hospitals", hospitals);
			// 得到用户的个人订单
			List<OrderRecords> orderRecords = orderRecordsService.findOrderRecordsByUserID(commonUser.getUserId());
			model.addAttribute("orderRecords", orderRecords);
			model.addAttribute("commonUser", commonUser);
			return "userCenter/userCenter";
		}
		return "userCenter/userCenter";
	}

	//确认订单
    @RequestMapping(value = "/okOrder/{id}", method = RequestMethod.POST)
    @ResponseBody
    public String okOrder( @PathVariable(value = "id") int id){
        //数据处理
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(orderRecordsService.orderIsOK(id)){
            resultMap.put("addResult", "true");
        }else{
            resultMap.put("addResult", "false");
        }
        return JSONArray.toJSONString(resultMap);
    }
	//取消 与 确认
	@RequestMapping(value = "/outOrder", method = RequestMethod.POST)
	@ResponseBody
	public String outOrder(@RequestParam("id") Integer id, @RequestParam("state") Integer state){
		//数据处理
		HashMap<String, String> resultMap = new HashMap<String, String>();
		if(state == 1) {
			if(orderRecordsService.orderIsOK(id)){
				resultMap.put("updateResult", "true");
			}else{
				resultMap.put("updateResult", "false");
			}
		} else {
			if(orderRecordsService.cancelOrder(id)>0){
				//取消成功 修改医生预约时段状态
				OrderRecords orderRecords1 = orderRecordsService.selectOrderSta1(id);//查找订单信息
				Doctor doctor = doctorService.findDoctorByName(orderRecords1.getDoctorName(),orderRecords1.getOfficesName(),orderRecords1.getHospitalName());//跟据医院名、科室名、医生名字得到医生
				DoctoWork doctoWork = doctoWorkService.selecrByIdAndDateOne(doctor.getId(), orderRecords1.getTransactDate());//根据医生ID、和日期得到预约状态
				if(orderRecords1.getTransactTime().equals("8:00-11:00")){
					doctoWork.setTimeS("0");
				}else if(orderRecords1.getTransactTime().equals("13:00-15:00")){
					doctoWork.setTimeZ("0");
				}else {
					doctoWork.setTimeX("0");
				}
				doctoWork.setGmtModified(new Date());
				doctoWorkService.updateByIdAndDate(doctoWork);
				resultMap.put("updateResult", "true");
			}else{
				resultMap.put("updateResult", "false");
			}
		}
		return JSONArray.toJSONString(resultMap);
	}



    @RequestMapping(value="/order/list.html")
	public String getUserList(Model model, HttpServletRequest request, OrderRecords queryOrder){
		Admin admin = (Admin) request.getSession().getAttribute("adminSession");
		Doctor doctor = (Doctor) request.getSession().getAttribute("doctorSession");
		List<OrderRecords> orderList = new ArrayList<>();
		if (null != admin && admin.getRank() > 1) {
			orderList = orderRecordsService.query(queryOrder);
		} else if (null != admin) {
			queryOrder.setHospitalName(admin.getHospitalName());
			orderList = orderRecordsService.query(queryOrder);

		} else if (null == admin && doctor != null) {
			queryOrder.setHospitalName(doctor.getHospitalName());
			queryOrder.setDoctorName(doctor.getDoctorName());
			queryOrder.setOfficesName(doctor.getOfficesName());
			orderList = orderRecordsService.query(queryOrder);
		}
		model.addAttribute("qOrder",queryOrder);
		model.addAttribute("orderList", orderList);
		return "bk/orderlist";
	}
}
